﻿using Microsoft.Phone.UserData;
using MobiSms.DataModel;
using MobiSms.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace MobiSms.ViewModel
{
    public class HomeViewModel : MainViewModel
    {
        private Contacts contacts = new Contacts();

        public HomeViewModel()
        {
            
            contacts.SearchCompleted -= contacts_SearchCompleted;
            contacts.SearchCompleted += contacts_SearchCompleted;
            if (!IsDesignMode && GlobalSettings.ShowRecentBirthday)
            {
                contacts.SearchAsync("", FilterKind.None, null);
            }
            if (!IsDesignMode)
            {
                //Invoke(typeof(SampleData), "Insert", null);
                Invoke(typeof(ReplyViewModel), "GetUnreadMessages", null);
            }
        }

        void contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
        {
            IEnumerable<Contact> items = e.Results.Where(c => c.Birthdays != null && c.Birthdays.Count() > 0);
            foreach (Contact item in items)
            { 
                DateTime original = item.Birthdays.FirstOrDefault();
                DateTime birthday = new DateTime(DateTime.Now.Year, original.Month, original.Day);
                if (birthday > DateTime.Today && birthday < DateTime.Today.AddDays(GlobalSettings.NotifyDays))
                {
                    RecentBirthdayContacts++;
                }
            }
        }

        public ObservableCollection<ReplyInfo> ItemsOfUnreadReply
        {
            get
            {
                if (IsDesignMode)
                {
                    return null;
                }
                if (Database.CollectionOfReplies.Count() > 0)
                {
                    return new ObservableCollection<ReplyInfo>(Database.CollectionOfReplies.Where(r => r.Status == ReplyMessageStatusValue.Unread));
                }
                return null;
            }
        }

        private int _recentBirthdayContacts = 0;
        public int RecentBirthdayContacts
        {
            get { return _recentBirthdayContacts; }
            set
            {
                _recentBirthdayContacts = value;
                RaisePropertyChanged(() => RecentBirthdayContacts);
            }
        }

        
    }
}
